package com.kuangstudy.controller.upload;

import com.kuangstudy.service.upload.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangfushuai
 * @description 本地文件上传
 * @since 2022/4/18 09:28
 **/
@Controller
public class UploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author zhangfushuai
     * @description 对接editor，实现上传文章内容图片
     * @since 2022/4/18 09:45
     * 参数 file
     * 参数 request
     **/
    @PostMapping("/api/local/mdupload")
    @ResponseBody
    public Map<String, Object> uploadmdupload(@RequestParam("editormd-image-file") MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
        if (file.isEmpty()) {
            return null;
        }
        String dir = request.getParameter("dir");
        if (StringUtils.isEmpty(dir)) {
            dir = "course";
        }
        // handler调用文件上传的service 得到文件的虚拟路径
        String filepath = uploadService.uploadImg(file, dir);
        Map<String, Object> map = new HashMap<>();
        map.put("path", filepath);
        map.put("url", filepath);
        map.put("success", "1");
        map.put("message", "upload success!");
        return map;
    }

    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author zhangfushuai
     * @description 对接WebUploader，实现上传文章封面图片
     * @since 2022/4/18 09:46
     * 参数 file
     * 参数 request
     **/
    @PostMapping("/api/local/uploadjson")
    @ResponseBody
    public Map<String, Object> uploadJson(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, ServletException {
        if (file.isEmpty()) {
            return null;
        }
        String dir = request.getParameter("dir");
        if (StringUtils.isEmpty(dir)) {
            dir = "course";
        }
        // handler调用文件上传的service 得到文件的虚拟路径
        String filepath = uploadService.uploadImg(file, dir);
        Map<String, Object> map = new HashMap<>();
        map.put("path", filepath);
        map.put("url", filepath);
        return map;
    }
}
